import progress from 'nprogress';
import { useStore } from '@/store';
import mainRoutesFn from '@/router/main';
import { APP_CONFIG } from '@/jiessConfig/consts';
import tokenCookie from '@/assets/utils/cookies/token';
const { routeLogin, title } = APP_CONFIG;
progress.configure({ showSpinner: false });

function setDomTitle(label) {
	document.title = `${label} - ${title}`;
}

function toSetTitle({ meta }) {
	if (meta?.label) setDomTitle(meta.label);
}

function routerError(err) {
	console.dir(err);
	tokenCookie.remove();
	progress.done();
}

function toUseTab(to) {
	const store = useStore();
	const { useTab, name, label } = to.meta;
	if (useTab) store.setCurrentTab({ name, label });
}
async function toCheckToken(to, router) {
	const { noAuth } = to.meta;
	if (!noAuth) {
		const token = tokenCookie.get();
		try {
			if (token) {
				await handleTokenExist(to, router);
			} else {
				await handleTokenNotExist(to);
			}
		} catch (newto) {
			return Promise.reject(newto);
		}
	}
}

async function handleTokenExist(to, router) {
	let store = useStore();
	let { accountInfo } = store;
	if (to.path === routeLogin.path) {
		return Promise.reject({ path: '/' });
	} else {
		if (!Object.keys(accountInfo).length) {
			try {
				await store.getAccountInfo();
				router.addRoute((await mainRoutesFn()));
				// hack方法 确保正确应用路由
				return Promise.reject({ ...to, replace: true });
			} catch (error) {
				await new Promise(resolve => setTimeout(resolve, 1000));
				routerError(error);
				return Promise.reject({ path: routeLogin.path });
			}
		}
	}
}

function handleTokenNotExist(to) {
	if (to.path !== routeLogin.path) {
		return Promise.reject({ path: routeLogin.path });
	}
}
async function toCheckRoute(to, from) {
	let store = useStore();
	if (to.path === from.path) {
		// return Promise.reject(false);
	} else if (store.routeCleanCache) {
		await store.cleanToRouteCache(to.name);
	}
	store.setRouteCleanCache(true);
}

export function interceptor(router) {
	router.onError(routerError);
	router.beforeEach(async (to, from, next) => {
		const store = useStore();
		progress.start();
		try {
			await toCheckRoute(to, from);
			if (import.meta.env.VITE_ACCESS_MODE === 'login') {
				await toCheckToken(to, router);
			} else {
				await handleTokenExist(to, router)
			}
			next();
			toUseTab(to);
			toSetTitle(to);
			store.addRouteCache(to);
			store.setRouteInfo({ to, from });
		} catch (error) {
			next(error);
		}
	});
	router.afterEach(() => progress.done());
}